#!/usr/bin/perl


# Script which in theory interfaces a MSS, heavily modified in order to
# support the Virtual Mass Storage System semantics.
# All the requests which slip outside of the calling xrootd server must be
# redirected to the local file system

use Time::Local;
use Errno;

%Month = ('Jan', 0, 'Feb', 1, 'Mar', 2, 'Apr', 3, 'May', 4, 'Jun', 5,
	  'Jul', 6, 'Aug', 7, 'Sep', 8, 'Oct', 9, 'Nov', 10, 'Dec', 11);

$command = $ARGV[0];


if ( $command eq "create" ) {
    $rc = 0;

    $ret = $rc."\n";
    print $ret;
    exit;
}

if ( $command eq "dlist" ) {
    $file = "$ENV{LOCALROOT}/$ENV{LOCALPATHPFX}/".GetPureFilename($ARGV[0]);
    $list=`ls -1 $file`;
    $rc = $? >> 8;
    if ($rc != 0) {
       $rc = Errno::ENOENT;
    }

    
    $ret = $rc."\n".$list;
    print $ret;
    exit;
}

if ( $command eq "mv" ) {
    $rc = 0;

    $ret = $rc."\n";
    print $ret;
    exit;
}

if ( $command eq "rm" ) {
    $rc = 0;

    $ret = $rc."\n";
    print $ret;
    exit;
}

if ( $command eq "statx" ) {
    $stats = "";
    $file = "$ENV{LOCALROOT}/$ENV{LOCALPATHPFX}/".GetPureFilename($ARGV[1]);

    @ans = `stat -c '%A 0 %u %g %X %Z %Y %B %b' $file`;
    $rc = $? >> 8;

    #print " @ans\n\n";

    if ($rc == 0) {
	$ftype="f";
	substr($ans[0], 0, 1) = "";
	$stats = $ftype." @ans";
    } else {
	$rc = Errno::ENOENT;
	$stats = "---";
    }

    $ret = $rc."\n".$stats;
    print "$ret\n";
    exit;
}



sub GetClusterPrefix {
    my ($url) = @_;

    if ($url =~ "root\:\/\/(.*)\/\/") {
       return $1;
    }
    return "";
}


sub GetPureFilename {
    my ($url) = @_;
    if ($url =~ "root\:\/\/(.*)\/\/(.*)") {
       return "\/$2";
    }
    return $url;
}

sub unixTime {
    @input = @_;
    $mon = $Month{$input[4]};
    $mday = $input[5];
    ($hours, $min, $sec) = split /:/, $input[6];
    $year = $input[7] - 1900;
    $time = timelocal($sec,$min,$hours,$mday,$mon,$year);
    return $time;
}


